package com.valten.controller;

import com.valten.model.Product;
import com.valten.model.ResponseEnum;
import com.valten.pojo.response.R;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
public class ProductController {
   private static final Map<String, Product> PRODUCT_REPO = new HashMap<>();
   static {
      Product honey = new Product();
      honey.setId("1");
      honey.setName("Honey");
      PRODUCT_REPO.put(honey.getId(), honey);

      Product almond = new Product();
      almond.setId("2");
      almond.setName("Almond");
      PRODUCT_REPO.put(almond.getId(), almond);
   }

   @GetMapping(value = "/product/{id}")
   public R<Product> getProduct(@PathVariable("id") String id) {
      Product product = PRODUCT_REPO.get(id);
      ResponseEnum.PRODUCT_NOT_FOUND.assertNotNull(product);
      return new R<>(product);
   }

   @PutMapping(value = "/product/{id}")
   public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
      Product pro = PRODUCT_REPO.get(id);
      ResponseEnum.PRODUCT_NOT_FOUND.assertNotNull(pro);
      PRODUCT_REPO.remove(id);
      product.setId(id);
      PRODUCT_REPO.put(id, product);
      return new ResponseEntity<>("Product is updated successfully.", HttpStatus.OK);
   }
}

